package com.cloud.school.bus.teacherhelper.modules.home.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ViewFlipper;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.BaseErrorListener;
import com.android.support.jhf.network.BaseStateListener;
import com.android.support.jhf.network.IErrorListener;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.utils.ScreenUtils;
import com.android.support.jhf.utils.ToolUtils;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.base.BaseLinearLayout;
import com.cloud.school.bus.teacherhelper.base.anim.swap3d.Constants;
import com.cloud.school.bus.teacherhelper.base.anim.swap3d.RotationHelper;
import com.cloud.school.bus.teacherhelper.base.database.AllPictureIgnoreDB;
import com.cloud.school.bus.teacherhelper.base.database.TeacherPictureIgnoreDB;
import com.cloud.school.bus.teacherhelper.base.database.UploadFileDB;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomAlertDialog;
import com.cloud.school.bus.teacherhelper.base.utils.PictureUtil;
import com.cloud.school.bus.teacherhelper.base.view.TitleNavBarView;
import com.cloud.school.bus.teacherhelper.entitys.Picture;
import com.cloud.school.bus.teacherhelper.entitys.Student;
import com.cloud.school.bus.teacherhelper.entitys.UploadFile;
import com.cloud.school.bus.teacherhelper.entitys.LoginSetting.PhotoTag;
import com.cloud.school.bus.teacherhelper.modules.HomeMenuFragment;
import com.cloud.school.bus.teacherhelper.modules.home.BigPictureActivity;
import com.cloud.school.bus.teacherhelper.modules.home.SendFileToStuActivity;
import com.cloud.school.bus.teacherhelper.modules.home.adapter.PictureThumbnailsAdapter;
import com.cloud.school.bus.teacherhelper.modules.notice.adapter.StuSelectAdapter;
import com.cloud.school.bus.teacherhelper.modules.uploadlist.UploadListFragment;
import com.cloud.school.bus.teacherhelper.modules.uploadlist.uploadutils.UploadFileUtils;
//import com.cloud.school.bus.teacherhelper.modules.uploadlist.uploadutils.UploadUtils;
import com.cloud.school.bus.teacherhelper.protocol.classstudent.GetClassinfoRequest;
import com.cloud.school.bus.teacherhelper.protocol.classstudent.GetClassinfoResponse;
import com.cloud.school.bus.teacherhelper.protocol.statistics.UploadFileRequest;
import com.cloud.school.bus.teacherhelper.protocol.statistics.UploadFileResponse;

/**
 * 选择同学发送文件
 * 
 * @author lenovo
 * 
 */
public class SelectedStuView extends BaseLinearLayout implements Constants {

	private ViewPager mViewPager;
	private PictureThumbnailsAdapter mPictureThumbnailsAdapter;
	private GridView mGridView;
	private StuSelectAdapter mStuSelectAdapter;
	private TextView mContentTextView;
	private TextView mPictureNumberTextView;
	private ViewFlipper mViewFlipper;
	private EditContentView mEditContentView;
	private TitleNavBarView mTitleNavBarView;

	private RotationHelper rotationHelper;

	private List<Picture> mPictures;

	private List<UploadFile> mUploadFiles = new ArrayList<UploadFile>();
	/** 0表示所有照片，1表示相机拍摄 */
	private int mFlag = 0;

	public SelectedStuView(Context context, List<Picture> pictures,
			ViewFlipper viewFlipper, int flag) {
		super(context);
		mPictures = pictures;
		mViewFlipper = viewFlipper;
		mFlag = flag;
		init();
	}

	public SelectedStuView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {

		LayoutInflater.from(mContext).inflate(R.layout.view_selected_stu, this,
				true);

		rotationHelper = new RotationHelper(SelectedStuView.this);

		mViewPager = (ViewPager) findViewById(R.id.viewPager);
		mPictureThumbnailsAdapter = new PictureThumbnailsAdapter(mContext,
				mPictures);
		mViewPager.setAdapter(mPictureThumbnailsAdapter);
		ViewGroup pagerLayout = (ViewGroup) findViewById(R.id.pagerLayout);
		int height = (ScreenUtils.getScreenBounds(mContext)[1] - ToolUtils
				.dipToPx(mContext, 45)) / 2;
		DebugLog.logI("viewpager height : " + height);
		pagerLayout.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, height));

		mContentTextView = (TextView) findViewById(R.id.contentTextView);
		mPictureNumberTextView = (TextView) findViewById(R.id.pictureNumberTextView);
		mPictureNumberTextView.setText("1/" + mPictures.size());

		for (int i = 0; i < mPictures.size(); i++) {
			UploadFile uploadFile = new UploadFile();
			uploadFile.picPathString = mPictures.get(i).getPicturePath();
			uploadFile.picSizeString = getPicSize(uploadFile.picPathString)
					+ "";
			uploadFile.picFileString = getPicName(uploadFile.picPathString);
			uploadFile.studentIdList = new ArrayList<String>();
			uploadFile.classuid = mApplication.mClassInfo.uid;
			uploadFile.intro = null;
			uploadFile.photoTag = null;
			uploadFile.teacherid = mApplication.mTeacher.teacherid;
			mUploadFiles.add(uploadFile);
		}

		mGridView = (GridView) findViewById(R.id.gridView);
		mStuSelectAdapter = new StuSelectAdapter(mContext,
				mApplication.mStudentList, mUploadFiles, mViewPager);
		mStuSelectAdapter.clearSelected();
		mGridView.setAdapter(mStuSelectAdapter);

		setListener();
		setTitleNavBar();
	}

	private String getPicName(String picPathString) {
		String picNameString = "";
		picNameString = picPathString
				.substring(picPathString.lastIndexOf("/") + 1);
		return picNameString;
	}

	private int getPicSize(String picPathString) {
		int size = 0;
		try {
			picPathString = picPathString.replace("file:///", "/");
			FileInputStream inputStream = new FileInputStream(new File(
					picPathString));
			try {
				size = inputStream.available();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return size;
	}

	private void refreshUiData(int currentPictureIndex) {
		UploadFile uploadFile = mUploadFiles.get(currentPictureIndex);
		mStuSelectAdapter.clearSelected();
		if (null != uploadFile.studentIdList
				&& 0 != uploadFile.studentIdList.size()) {
			List<String> studentid = uploadFile.studentIdList;
			if (studentid.size() > 0) {
				int i = 0;
				for (i = 0; i < mApplication.mStudentList.size(); i++) {
					Student student = mApplication.mStudentList.get(i);
					for (int j = 0; j < studentid.size(); j++) {
						if (student.studentid.equals(studentid.get(j))) {
							student.isSelected = true;
							break;
						}
					}
				}

			} else {
			}
		} else {
		}
		mStuSelectAdapter.notifyDataSetChanged();

		mPictureNumberTextView.setText((currentPictureIndex + 1) + "/"
				+ mPictures.size());
		setContent(uploadFile.photoTag, uploadFile.intro);

		if (null != mEditContentView) {
			if (mContext.getString(R.string.apply_all).equals(
					uploadFile.photoTag)) {
				// mEditContentView.getEditContentAdapter().allSelected();
			} else if (!TextUtils.isEmpty(uploadFile.photoTag)) {
				List<PhotoTag> photoTagZH = mApplication.mLoginSetting.photoTagList
						.get(0);
				List<PhotoTag> photoTagEN = mApplication.mLoginSetting.photoTagList
						.get(1);
				int photoTagIndex = -1;
				for (int i = 0; i < photoTagZH.size(); i++) {
					if (photoTagZH.get(i).photoTag.equals(uploadFile.photoTag)) {
						photoTagIndex = i;
						break;
					}
				}
				for (int i = 0; i < photoTagEN.size(); i++) {
					if (photoTagEN.get(i).photoTag.equals(uploadFile.photoTag)) {
						photoTagIndex = i;
						break;
					}
				}
				if (-1 != photoTagIndex) {
					DebugLog.logI("photoTagIndex : " + photoTagIndex);
					mEditContentView.setSelectedIndex(photoTagIndex);
				} else {
					mEditContentView.getEditContentAdapter().clearAllSelected();
				}
			} else {
				mEditContentView.getEditContentAdapter().clearAllSelected();
			}

			mEditContentView.getContentEditText().setText(uploadFile.intro);
		}
	}

	public void setContent(String photoTag, String contentString) {
		if (TextUtils.isEmpty(photoTag) && TextUtils.isEmpty(contentString)) {
			mContentTextView.setVisibility(View.GONE);
			mContentTextView.setText("");
		} else {
			mContentTextView.setVisibility(View.VISIBLE);
			mContentTextView.setText(photoTag + " " + contentString);
		}
	}

	protected void setTitleNavBar() {
		mTitleNavBarView = (TitleNavBarView) findViewById(R.id.titleNavBarView);
		mTitleNavBarView.setMessage(mContext.getString(R.string.in_the_photo));
		mTitleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 返回
				cancel();
			}
		});
		mTitleNavBarView.setRightButtonImageString(
				R.drawable.btn_title_upload_pic_xml, "", R.color.text_blue);
		mTitleNavBarView.setRightButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int i = 0;
				for (i = 0; i < mUploadFiles.size(); i++) {
					UploadFile uploadFile = mUploadFiles.get(i);
					if (0 == uploadFile.studentIdList.size()) {
						break;
					}
				}
				if (mUploadFiles.size() == i) {
					// 都关联了学生
					// 返回上一级
					mApplication.imageLoaderInit(80, 80);
					((Activity) mContext).setResult(Activity.RESULT_OK);
					((Activity) mContext).finish();
					saveUploadFile();
				} else {
					HandlerToastUI.getHandlerToastUI(mContext, "还有照片没有关联学生");
				}

			}
		});
	}

	private void saveUploadFile() {
		// new Thread(new Runnable() {
		//
		// @Override
		// public void run() {
		// 保存数据
//		UploadUtils.getUploadUtils().setContext(mContext);
//		UploadUtils.getUploadUtils().setUploadFileDB(mUploadFiles);
//		UploadUtils.getUploadUtils().uploadFileService();
		UploadFileUtils.getUploadUtils().setContext(mContext);
		UploadFileUtils.getUploadUtils().setUploadFileDB(mUploadFiles);
		UploadFileUtils.getUploadUtils().uploadFileService();
		// }
		// }).start();
	}

	public void setEditContentView(EditContentView editContentView) {
		mEditContentView = editContentView;
		mEditContentView.setUploadFile(mUploadFiles.get(mViewPager
				.getCurrentItem()));
		mEditContentView.setUploadFileList(mUploadFiles);
	}

	protected void setListener() {
		Button contentButton = (Button) findViewById(R.id.contentButton);
		contentButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				rotationHelper.applyRotation(Constants.viewB, 0, 90);
				// mViewFlipper.setDisplayedChild(SendFileToStuActivity.EDIT_CONTENT);
			}
		});

		mPictureThumbnailsAdapter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				int position = mViewPager.getCurrentItem();
				List<Picture> pictures = new ArrayList<Picture>();
				pictures.add(mPictures.get(position));
				Intent intent = new Intent(mContext, BigPictureActivity.class);
				intent.putExtra("pictureList", (ArrayList<Picture>) pictures);
				intent.putExtra("position", position);
				intent.putExtra("flag", 1);
				((Activity) mContext).startActivityForResult(intent, 0);
			}

		});

		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				mPictureNumberTextView.setText((arg0 + 1) + "/"
						+ mPictures.size());

				mEditContentView.setUploadFile(mUploadFiles.get(mViewPager
						.getCurrentItem()));
				// if (mUploadFiles.size() > 0)
				// mStuSelectAdapter.setUploadFile(mUploadFiles.get(mViewPager
				// .getCurrentItem()));
				refreshUiData(mViewPager.getCurrentItem());
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 0: {
			// 查看大图返回
			switch (resultCode) {
			case Activity.RESULT_OK: {
				// 删除图片成功返回
				if (null != data) {
					int delPicIndex = data.getIntExtra("DelPicIndex", -1);
					if (-1 != delPicIndex) {
						mPictures.remove(delPicIndex);
						mUploadFiles.remove(delPicIndex);

						if (0 == mPictures.size()) {
							mApplication.imageLoaderInit(80, 80);
							((Activity) mContext).finish();
							return;
						} else {
						}
						mPictureThumbnailsAdapter.notifyDataSetChanged();

						mPictureNumberTextView
								.setText((mViewPager.getCurrentItem() + 1)
										+ "/" + mPictures.size());
						refreshUiData(mViewPager.getCurrentItem());
					}
				}
				break;
			}
			case Activity.RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		default:
			break;
		}
	}

	private void cancel() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog.setTitleMessage("提示", Color.BLACK);
		customAlertDialog.setMessage("取消发送照片");
		customAlertDialog.setLeftButton("是", new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mApplication.imageLoaderInit(80, 80);
				((Activity) mContext).finish();
			}
		});
		customAlertDialog.setRightButton("否", new OnClickListener() {

			@Override
			public void onClick(View arg0) {

			}
		});
		customAlertDialog.show();
	}

	// private void uploadFile(final UploadFile uploadFile) {
	//
	// String picPathString = uploadFile.picPathString
	// .replace("file:///", "/");
	// StringBuilder studentIdStringBuilder = new StringBuilder();
	// if (uploadFile.studentIdList.size() > 0) {
	// for (int i = 0; i < uploadFile.studentIdList.size(); i++) {
	// studentIdStringBuilder.append(uploadFile.studentIdList.get(i)).append(",");
	// }
	// studentIdStringBuilder.delete(studentIdStringBuilder.length() - 1,
	// studentIdStringBuilder.length());
	// }
	//
	// String fname = null, fsize = null, fbody = null, fext = null;
	// if (!TextUtils.isEmpty(picPathString)) {
	// fbody = PictureUtil.getPicString(picPathString, 512);
	// fext = picPathString.substring(picPathString.lastIndexOf(".") + 1);
	// fname = picPathString.substring(picPathString.lastIndexOf("/") + 1);
	// fsize = fbody.length() + "";
	// }
	//
	// NetworkClient.getNetworkClient().PostRequest(
	// new UploadFileRequest(mContext.getApplicationContext(), fbody,
	// fname, studentIdStringBuilder.toString(),
	// mApplication.mClassInfo.uid, uploadFile.intro,
	// uploadFile.photoTag, mApplication.mTeacher.teacherid),
	// new UploadFileResponse() {
	// @Override
	// public void onResponse(
	// ResponseHandlerInterface responseHandlerInterface) {
	// DebugLog.logI("code : " + code);
	// if ("1".equals(code)) {
	// // 上传成功，更新上传列表
	// UploadFileDB uploadFileDB = UploadFileDB
	// .getUploadFileDB(mContext);
	// uploadFileDB.remove(uploadFile);
	// uploadFileDB.close();
	//
	// //刷新列表
	// Intent intent = new Intent();
	// intent.setAction(UploadListFragment.ACTION_UPDATE_UPLOAD_LIST);
	// mContext.sendBroadcast(intent);
	//
	// }
	// }
	// }, new BaseStateListener() {
	// }, null);
	// }

	@Override
	public void initSwapView() {
		// DebugLog.logI("initSwapView");
		init();
	}

	@Override
	public RotationHelper getRotationHelper() {
		// DebugLog.logI("getRotationHelper");
		return rotationHelper;
	}

	@Override
	public ViewGroup getViewGroup() {
		// DebugLog.logI("getViewGroup");
		return mViewFlipper;
	}

	@Override
	public int getSwapView() {
		// DebugLog.logI("getSwapView");
		return Constants.viewB;
	}

	@Override
	public void swapViewA() {
		// DebugLog.logI("swapViewA");
		mViewFlipper.setDisplayedChild(SendFileToStuActivity.SELECTED_STU);
	}

	@Override
	public void swapViewB() {
		// DebugLog.logI("swapViewB");
		mViewFlipper.setDisplayedChild(SendFileToStuActivity.EDIT_CONTENT);
		mEditContentView.getRotationHelper().applyRotation(Constants.viewB,
				-90, 0);
	}
}
